package com.ruanxie.utils;

import lombok.Data;
import org.bytedeco.javacv.Frame;
import org.bytedeco.javacv.FrameGrabber;
import org.bytedeco.javacv.Java2DFrameConverter;
import org.bytedeco.javacv.OpenCVFrameGrabber;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;


@Data
public class CameraCaputureUtil {
    private OpenCVFrameGrabber grabber;//获取本地的摄像头
        //OpenCVFrameGrabber grabber=new OpenCVFrameGrabber(0)
    /**
     * 开启摄像头
     */
    public void start()  {
        try {
            grabber.start();//启动摄像头
        } catch (FrameGrabber.Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 关闭摄像头
     */
    public void stop() throws FrameGrabber.Exception {
        grabber.stop();
    }

    /**
     * 获取当前摄像头的一帧，并保存到savePath
     * @param savePath
     */
    public void captureImage(String savePath)  {
        try {
            // 捕获摄像头的帧
            Frame frame = null;  // Cgrabber.grab() 方法用于捕获摄像头的帧，返回的是 Frame 对象。
            frame = grabber.grab();
                // 将 Frame 转换为 OpenCV 的 Mat 对象。Mat 是 OpenCV 中处理图像数据的核心类。
    //            OpenCVFrameConverter.ToMat converterToMat = new OpenCVFrameConverter.ToMat();
    //            Mat mat = converterToMat.convert(frame);  // Convert Frame to Mat

    //            canvas.showImage(frame);

            // 将帧转为文件
            Java2DFrameConverter converterToBufferedImage = new Java2DFrameConverter();
            BufferedImage img = converterToBufferedImage.convert(frame);

            // Save the captured image
            ImageIO.write(img, "jpg", new File(savePath));
        } catch (FrameGrabber.Exception e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
}
